package com.foo.common.base.service;

import java.io.IOException;
import java.io.Serializable;

import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

@Service
public class EhcacheService {

	private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

	private CacheManager cacheManager = null;
	private Ehcache ehcache = null;

	public EhcacheService() throws CacheException, IOException {
		logger.info("CacheManager init start.");
		cacheManager = CacheManager.newInstance(new ClassPathResource(
				"ehcache.xml").getInputStream());
		ehcache = cacheManager.getEhcache("myConfig");
		logger.info("CacheManager init success with hash:{}", this.toString());
	}

	public void remove(Serializable key) {
		ehcache.remove(key);
	}

	public void put(Element element) {
		ehcache.put(element);
	}

	public Element get(String key) {
		return ehcache.get(key);
	}

	public Element get(FooGenericService fooGenericService, String cacheKeyId) {
		Element element = ehcache.get(cacheKeyId);
		if (element != null) {
			return ehcache.get(cacheKeyId);
		}
		return ehcache.get(cacheKeyId);
	}

	@Override
	public String toString() {
		return super.toString();
	}

}
